package net.zdreamer.geracomium.utils.account;

import android.os.Handler;
import android.os.Message;
import android.util.Base64;

import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.JsonObjectRequest;
import com.android.volley.toolbox.JsonRequest;

import net.zdreamer.geracomium.application.BaseApplication;
import net.zdreamer.geracomium.utils.tools_utils.BCrypt;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.LinkedHashMap;
import java.util.Map;

/**
 * Created by xuhaitao on 14/11/21.
 */
public class LoginService {
    /**
     * 提交注册数据
     *
     * @param username
     * @param password
     * @param phoneNo
     * @param regsiturl
     */
    public static void RegistPost(String username, String password, String phoneNo, String regsiturl, final Handler handler) {
        RequestQueue requestQueue = BaseApplication.get().getRequestQueue();
        Map<String, String> map = new LinkedHashMap<String, String>();
        map.put("username", username);
        map.put("password", BCrypt.hashpw(password, BCrypt.gensalt(5)));
        map.put("phoneNo", phoneNo);
        map.put("userType", "Guardian");
        BaseApplication.get().setUserId(username);
        JSONObject jsonObject = new JSONObject(map);
        final Message msg = new Message();
        JsonRequest<JSONObject> jsonRequest = new JsonObjectRequest(Request.Method.POST,
                regsiturl, jsonObject,
                new Response.Listener<JSONObject>() {
                    @Override
                    public void onResponse(JSONObject response) {
                        System.out.println(response);
                        msg.arg1 = 201;
                        handler.sendMessage(msg);
                        try {
                            response.getString("sucess");

                        } catch (JSONException e) {
                            e.printStackTrace();
                        }
                    }
                }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                //  System.out.println(error.networkResponse);
                System.out.println("conde error");
                if (error.networkResponse != null) {
                    int code = error.networkResponse.statusCode;

                    msg.arg1 = code;
                    handler.sendMessage(msg);
                } else {
                    msg.arg1 = 0;
                    handler.sendMessage(msg);
                }
            }

        });
        requestQueue.add(jsonRequest);
    }

    /**
     * 登陆
     *
     * @param username
     * @param password
     * @param loginurl
     */
    public static String LogInPost(final String username, final String password, String loginurl) {

        HttpClient client = null;
        try {
            // 1.打开一个浏览器
            client = new DefaultHttpClient();
            // 2.输入网址
            HttpPost httpPost = new HttpPost(loginurl);

            String credentials = username + ":" + password;
            String base64EncodedCredentials = Base64.encodeToString(credentials.getBytes(), Base64.NO_WRAP);
            httpPost.addHeader("Authorization", "Basic " + base64EncodedCredentials);

            // 3.敲回车
            HttpResponse response = client.execute(httpPost);
            //  Log.e("login-url", httpPost.getURI() + "");
            int code = response.getStatusLine().getStatusCode();
            //  Log.e("result-code", code + "");
            if (code == 200) {
                return EntityUtils.toString(response.getEntity());
            } else {
                return null;
            }
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            if (client != null) {
                client.getConnectionManager().shutdown();
            }
        }
        return null;
    }

    /**
     * 登录专用
     */
    public static void loginServicce(final String userName, final String pwd,
                                     final Handler handler, final String loginurl) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                // TODO Auto-generated method stub
                String result = LogInPost(userName, pwd, loginurl);
                Message msg = new Message();

                if (result != null) {
                    String array = null;
                    try {
                        JSONObject object = new JSONObject(result);
                        array = object.getString("token");
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                    msg.arg1 = 1;
                    msg.obj = array;
                    // System.out.println(result);
                    handler.sendMessage(msg);
                } else {
                    msg.arg1 = 0;
                    handler.sendMessage(msg);
                }
            }
        }).start();
    }
}
